﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Bing.Maps;
using Windows.Devices.Geolocation;
using System.Net.Http;
using Windows.Data.Json;
using System.Threading.Tasks;

// Pour en savoir plus sur le modèle d'élément Page de base, consultez la page http://go.microsoft.com/fwlink/?LinkId=234237

namespace WS_Manager_ShopMob.Views
{
    /// <summary>
    /// Page de base qui inclut des caractéristiques communes à la plupart des applications.
    /// </summary>
    public sealed partial class TrajetPage : WS_Manager_ShopMob.Common.LayoutAwarePage
    {
        LocationCollection collections = new LocationCollection();
        Location myLocation = new Location();
        public TrajetPage()
        {
            getPosition();
            this.InitializeComponent();
        }

        /// <summary>
        /// Remplit la page à l'aide du contenu passé lors de la navigation. Tout état enregistré est également
        /// fourni lorsqu'une page est recréée à partir d'une session antérieure.
        /// </summary>
        /// <param name="navigationParameter">Valeur de paramètre passée à
        /// <see cref="Frame.Navigate(Type, Object)"/> lors de la requête initiale de cette page.
        /// </param>
        /// <param name="pageState">Dictionnaire d'état conservé par cette page durant une session
        /// antérieure. Null lors de la première visite de la page.</param>
        protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            ViewModels.CommandeViewModel cvm = navigationParameter as ViewModels.CommandeViewModel;
            Location loc = await getLocation(cvm);
            collections.Add(loc);
            getItineraire();
            this.DataContext = cvm;
        }

        /// <summary>
        /// Conserve l'état associé à cette page en cas de suspension de l'application ou de la
        /// suppression de la page du cache de navigation. Les valeurs doivent être conformes aux
        /// exigences en matière de sérialisation de <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">Dictionnaire vide à remplir à l'aide de l'état sérialisable.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private async void getPosition()
        {
            Geolocator geolocator = new Geolocator();
            var pos = await geolocator.GetGeopositionAsync();
            Location location = new Location(pos.Coordinate.Latitude, pos.Coordinate.Longitude);
            collections.Add(location);
            //Center map view on current location. 
            map.SetView(location, 15.0f);
            MapLayer.SetPosition(pushPin, location);
            myLocation = location;
        }

        private async Task<Location> getLocation(ViewModels.CommandeViewModel cvm)
        {
            string uri = "http://dev.virtualearth.net/REST/v1/Locations/" + cvm.Client.Adresse + " " + cvm.Client.Cp + " " + cvm.Client.Ville + "?maxResults=1&key=Ai1fgA62BvHepJJP47IuQ_KsxXbYgfPZRCH_vl3OI4YG9olsSn2mzshkD9lJUgUH";
            var client = new HttpClient();
            var result = await client.GetStringAsync(uri);
            JsonValue value = Windows.Data.Json.JsonValue.Parse(result);

            var resources = value.GetObject()["resourceSets"].GetArray()[0].GetObject()["resources"].GetArray();
            Location location = new Location();
            foreach (var item in resources)
            {
                var name = item.GetObject()["name"].GetString();

                var coordinates = item.GetObject()["point"].GetObject()["coordinates"].GetArray();

                location.Latitude = coordinates[0].GetNumber();
                location.Longitude = coordinates[1].GetNumber();
                Pushpin pin = new Pushpin();
                MapLayer.SetPosition(pin, location);
                map.Children.Add(pin);
            }
            return location;
        }

        private async void getItineraire()
        {
            string s = "";
            int i = 0;
            foreach (var loc in collections)
            {
                s += "&wp." + i + "=" + loc.Latitude.ToString().Replace(',', '.') + " ," + loc.Longitude.ToString().Replace(',', '.');
                i++;
            }
            string uri = "http://dev.virtualearth.net/REST/v1/Routes/Driving?" + s + "&avoid=minimizeTolls&routePathOutput=points&key=Ai1fgA62BvHepJJP47IuQ_KsxXbYgfPZRCH_vl3OI4YG9olsSn2mzshkD9lJUgUH";
            var client = new HttpClient();
            var result = await client.GetStringAsync(uri);
            JsonValue value = Windows.Data.Json.JsonValue.Parse(result);
            var coordinates = value.GetObject()["resourceSets"].GetArray()[0]
                      .GetObject()["resources"].GetArray()[0]
                      .GetObject()["routePath"]
                      .GetObject()["line"]
                      .GetObject()["coordinates"].GetArray();
            var collecs = new LocationCollection();

            foreach (var coordinate in coordinates)
            {
                var latitude = coordinate.GetArray()[0].GetNumber();
                var longitude = coordinate.GetArray()[1].GetNumber();

                var location = new Location(latitude, longitude);
                collecs.Add(location);
            }

            MapPolyline polyline = new MapPolyline();
            polyline.Locations = collecs;
            polyline.Color = Windows.UI.Colors.Blue;
            polyline.Width = 5;
            MapShapeLayer layer = new MapShapeLayer();
            layer.Shapes.Add(polyline);
            map.ShapeLayers.Add(layer);
        }
    }
}
